import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ErrorDemo {


    private static List<String> errorPatterns = new ArrayList<>();

    static {
        errorPatterns.add("\\s{1,}line\\s{1,}\\d{1,}");
    }

    private String splitAndMinus(String line) {
        //you will get ["", "line", "3"]
        String[] parts = line.split(" ");
        if (parts.length >= 2) {
            int parseInt = Integer.parseInt(parts[parts.length - 1].trim());
            parseInt -= 1;
            return " " + parts[1] + " " + parseInt;
        }
        return line;
    }

    /**
     * 自定义替换，
     *
     * @param matcher
     * @param replacement
     * @param isUnique
     * @return
     */
    private String replaceAll(Matcher matcher, String originalScript, String replacement,
                              Boolean isUnique) {
        matcher.reset();
        boolean result = matcher.find();
        if (result) {
            StringBuffer sb = new StringBuffer();
            do {
                if (isUnique) {
                    //输入unique 可以部指定replacement
                    replacement = splitAndMinus(matcher.group());
                }
                matcher.appendReplacement(sb, replacement);
                result = matcher.find();
            } while (result);
            matcher.appendTail(sb);
            return sb.toString();
        } else {
            return originalScript;
        }
    }


    private String wrapperErrorMsg(String script) {
        Pattern p = Pattern.compile(errorPatterns.get(0));
        Matcher m = p.matcher(script);
        script = replaceAll(m, script, "", Boolean.TRUE);
        return script;
    }

    public static void main(String[] args) {
        String errorMsg = "Traceback (most recent call last):\n"
                + "  File \"/mnt/data2/yarn/nm/usercache/root/appcache/application_1601361253087_3860/container_1601361253087_3860_01_000001/tmp/1626769449460-1/zeppelin_python.py\", line 157, in \n"
                + "    exec(code, _zcUserQueryNameSpace)\n"
                + "  File \"\", line 2, in \n"
                + "NameError: name 'a22s' is not defined";
        String cStr = "Aaron1A啊23123";
//        System.out.println(StringUtil.hasChinese(cStr));
//        String result = new ErrorDemo().wrapperErrorMsg(errorMsg);
//        System.out.println(result);

    }
}
